﻿using Minecraft.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Minecraft.ServerHall
{
	public class ServerThreadPoolBase
	{
		public void Start(string threadPoolName,
			MinecraftSession paramSession,
			Action<MinecraftSession> beforeAction,
			Action<MinecraftSession> runningAction,
			Action<MinecraftSession> afterAction)
		{
			ThreadPool.QueueUserWorkItem(threadObj =>
			{
				var threadSession = threadObj as MinecraftSession;
				if (JsonConfig.Value.IsConsoleWrite)
				{
					Console.ForegroundColor = ConsoleColor.DarkYellow;
					Console.WriteLine($"----------------【{threadPoolName}】线程启动 playerId：【{threadSession.minecraftSessionInfo.player.PlayerId}】 时间：【{DateTimeOffset.Now.ToStr()}】");
					Console.ResetColor();
				}
				beforeAction?.Invoke(threadSession);
				while (true)
				{
					Thread.Sleep(1);
					if (threadSession.minecraftSessionInfo.IsLoginAfterThreadRunning)
					{
						runningAction?.Invoke(threadSession);
					}
					else
					{
						if (JsonConfig.Value.IsConsoleWrite)
						{
							Console.ForegroundColor = ConsoleColor.DarkYellow;
							Console.WriteLine($"----------------【{threadPoolName}】线程退出 playerId：【{threadSession.minecraftSessionInfo.player.PlayerId}】时间：【{DateTimeOffset.Now.ToStr()}】");
							Console.ResetColor();
						}
						afterAction?.Invoke(threadSession);
						return;
					}
				}
			}, paramSession);
		}
	}
}
